#include "qtch/qtch.h"
#include <memory>
#include<ucontext.h>





static qtch::Logger::ptr logger = QTCH_LOG_NAME("test");

void testfunc(){
    QTCH_LOG_INFO(logger) << "testfunc";
}

void test_swapcontent(){
    QTCH_LOG_INFO(logger) << "begin swapcontent";
    ucontext_t ctx_main,ctx_fun;
    getcontext(&ctx_main);
    getcontext(&ctx_fun);
    QTCH_LOG_INFO(logger) << "getcontext";
    char *stack = (char*)malloc(sizeof(char)*8192);
    ctx_main.uc_stack.ss_sp    = stack;
	ctx_main.uc_stack.ss_size  = 8192;
	ctx_main.uc_stack.ss_flags = 0;
	ctx_main.uc_link = &ctx_fun;

    makecontext(&ctx_main, testfunc, 0);
    QTCH_LOG_INFO(logger) << "makecontext";

    swapcontext(&ctx_fun,&ctx_main);
    QTCH_LOG_INFO(logger) << "swapcontext";

    QTCH_LOG_INFO(logger) << "end swapcontent";
}

void testAssert(){
    QTCH_ASSERT2(true,"test1");
    QTCH_ASSERT2(false,"test");
    QTCH_ASSERT(1==1);
}

void test_fiber_fun(){
    QTCH_LOG_INFO(logger) << "begin test_fiber_run";
    qtch::Fiber::yieldToHold();
    QTCH_LOG_INFO(logger) << " test_fiber_run 1";
    qtch::Fiber::yieldToHold();
}

void test_fiber(){
    QTCH_LOG_INFO(logger) << "test_fiber main begin";
    qtch::Fiber::ptr fiber(new qtch::Fiber(&test_fiber_fun));
    QTCH_LOG_INFO(logger) << "test_fiber 1";
    fiber->swapIn();
    QTCH_LOG_INFO(logger) << "test_fiber 2";
    fiber->swapIn();
    QTCH_LOG_INFO(logger) << "test_fiber 3";
    fiber->swapIn();
    QTCH_LOG_INFO(logger) << "test_fiber main end";
    QTCH_LOG_INFO(logger) << "fibers count = "<<qtch::Fiber::getFibersCount();
}

int main(){
    QTCH_LOG_INFO(logger) << "fibers count = "<<qtch::Fiber::getFibersCount();
    test_fiber();
    QTCH_LOG_INFO(logger) << "fibers count = "<<qtch::Fiber::getFibersCount();
}